package com.cjm.one.goods.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.cjm.one.custom.client.CustomerInfoClient;
import com.cjm.one.goods.mapper.GoodsCollectMapper;
import com.cjm.one.goods.mapper.GoodsDetailsMapper;
import com.cjm.one.goods.mapper.GoodsSkuMapper;
import com.cjm.one.goods.service.GoodsInfoService;
import com.cjm.one.goods.mapper.GoodsInfoMapper;
import com.cjm.one.model.common.ImportResult;
import com.cjm.one.model.goods.dto.GoodsInfoDto;
import com.cjm.one.model.goods.entity.GoodsCollect;
import com.cjm.one.model.goods.entity.GoodsDetails;
import com.cjm.one.model.goods.entity.GoodsInfo;
import com.cjm.one.model.goods.entity.GoodsSku;
import com.cjm.one.model.goods.enums.GoodsInfoStatusEnum;
import com.cjm.one.model.goods.enums.SortStrategyEnum;
import com.cjm.one.model.goods.vo.GoodsInfoVo;
import io.seata.spring.annotation.GlobalTransactional;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
* @author 29289
* @description 针对表【goods_info】的数据库操作Service实现
* @createDate 2024-09-05 16:07:00
*/
@Service
@Slf4j
public class GoodsInfoServiceImpl extends ServiceImpl<GoodsInfoMapper, GoodsInfo>
    implements GoodsInfoService{
    @Resource
    private GoodsInfoMapper goodsInfoMapper;

    @Resource
    private GoodsSkuMapper goodsSkuMapper;

    @Resource
    private GoodsDetailsMapper goodsDetailsMapper;
    @Resource
    private GoodsCollectMapper goodsCollectMapper;



    @Override
    public Page<GoodsInfo> pageList(Page<GoodsInfoVo> page, String name, Long categoryId) {
        Page<GoodsInfo> pages = goodsInfoMapper.pageList(page, name, categoryId);
        return pages;
    }

    @Override
    @GlobalTransactional
    public Boolean saveGoodsInfo(GoodsInfoDto goodsInfoDto) {
        //TODO: 事务
        // 保存商品信息 基本信息
        GoodsInfo goodsInfo = new GoodsInfo();
        BeanUtils.copyProperties(goodsInfoDto, goodsInfo);

         goodsInfoMapper.insert(goodsInfo);
//        System.out.println("goodsInfo = " + "陈积明2222");
//        System.out.println(1/0);
//        System.out.println("goodsInfo = " + "陈积明");
        // 保存sku信息
        List<GoodsSku> goodsSkuList = goodsInfoDto.getGoodsSkuList();
        for (GoodsSku goodsSku : goodsSkuList) {
            goodsSku.setGoodsId(goodsInfo.getId());

        }
        log.info("goodsSkuList:{}", goodsSkuList);
        goodsSkuMapper.insert(goodsSkuList);


        return true;
    }
    // 修改商品信息
    @Override
    @GlobalTransactional
    public Boolean updateGoodsInfoById(GoodsInfoDto goodsInfoDto) {
        //TODO: 事务
        GoodsInfo goodsInfo = new GoodsInfo();
        BeanUtils.copyProperties(goodsInfoDto, goodsInfo);
        goodsInfoMapper.updateById(goodsInfo);

        // 修改sku信息
        LambdaQueryWrapper<GoodsSku> goodsSkuLambdaQueryWrapper = new LambdaQueryWrapper<>();
        goodsSkuLambdaQueryWrapper.eq(GoodsSku::getGoodsId, goodsInfoDto.getId());
        int delete = goodsSkuMapper.delete(goodsSkuLambdaQueryWrapper);

            List<GoodsSku> goodsSkuList = goodsInfoDto.getGoodsSkuList();
            for (GoodsSku goodsSku : goodsSkuList) {
                goodsSku.setId(null);
                goodsSku.setGoodsId(goodsInfo.getId());

            }
            goodsSkuMapper.insert(goodsSkuList);


        // 修改详情信息
        return true;
    }

    @Override
    @GlobalTransactional
    public Boolean removeGoodsInfoById(Long id) {
        //TODO: 事务
        int i = goodsInfoMapper.deleteById(id);
        int delete = goodsSkuMapper.delete(new LambdaQueryWrapper<GoodsSku>().eq(GoodsSku::getGoodsId, id));
        int j = goodsDetailsMapper.delete(new LambdaQueryWrapper<GoodsDetails>().eq(GoodsDetails::getGoodsId, id));

        return j>0;
    }

    @Override
    public GoodsInfoVo getGoodsInfoById(Long id) {
        GoodsInfoVo goodsInfoVo = new GoodsInfoVo();
        BeanUtils.copyProperties(goodsInfoMapper.selectById(id), goodsInfoVo);
        LambdaQueryWrapper<GoodsSku> goodsSkuLambdaQueryWrapper = new LambdaQueryWrapper<>();
        goodsSkuLambdaQueryWrapper.eq(GoodsSku::getGoodsId, id);
        List<GoodsSku> goodsSkus = goodsSkuMapper.selectList(goodsSkuLambdaQueryWrapper);

        goodsInfoVo.setGoodsSkuList(goodsSkus);

        return goodsInfoVo;
    }

    @Override
    public List<GoodsInfo> listBatch(Long[] ids) {
        LambdaQueryWrapper<GoodsInfo> goodsInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        goodsInfoLambdaQueryWrapper.in(GoodsInfo::getId, ids);
        List<GoodsInfo> goodsInfos = goodsInfoMapper.selectList( goodsInfoLambdaQueryWrapper);
        return goodsInfos;
    }

    @Override
    public void exportGoods(List<Long> ids, HttpServletResponse response) throws IOException {

    }

    @Override
    public ImportResult importGoods(MultipartFile file) throws IOException {
        return null;
    }

//    public void exportGoods(List<Long> ids, HttpServletResponse response) throws IOException {
//
//        LambdaQueryWrapper<GoodsInfo> goodsInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        goodsInfoLambdaQueryWrapper.in(GoodsInfo::getId, ids);
//        List<GoodsInfo> goodsList = goodsInfoMapper.selectList(goodsInfoLambdaQueryWrapper);
//        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
//                .registerWriteHandler(new HorizontalCellStyleStrategy())
//                .build();
//
//        // 主表写入
//        WriteSheet mainSheet = EasyExcel.writerSheet(0, "商品信息")
//                .head(GoodsInfoDto.class)
//                .build();
//
//        // SKU子表
//        WriteSheet skuSheet = EasyExcel.writerSheet(1, "SKU明细")
//                .head(GoodsSku.class)
//                .build();
//
//        goodsList.forEach(goods -> {
//            GoodsExportDTO dto = convertToExportDTO(goods);
//            excelWriter.write(Collections.singletonList(dto), mainSheet);
//
//            if (CollectionUtils.isNotEmpty(goods.getGoodsSkuList())) {
//                List<SkuExportDTO> skuDtos = convertSkuList(goods.getGoodsSkuList());
//                excelWriter.write(skuDtos, skuSheet);
//            }
//        });
//
//        excelWriter.finish();
//    }
//
//    // 批量导入实现
//    public ImportResult importGoods(MultipartFile file) throws IOException {
//        ImportResult result = new ImportResult();
//
//        AnalysisEventListener<GoodsInfoVo> listener = new AnalysisEventListener<>() {
//            private List<GoodsInfoVo> successList = new ArrayList<>();
//            private List<GoodsInfoVo> errorList = new ArrayList<>();
//
//            @Override
//            public void invoke(GoodsInfoVo data, AnalysisContext context) {
//                if (validateData(data)) {
//                    successList.add(data);
//                } else {
//                    errorList.add(buildError(data, "数据校验失败"));
//                }
//            }
//
//            @Override
//            public void doAfterAllAnalysed(AnalysisContext context) {
//                batchInsert(successList);
//                result.setSuccessCount(successList.size());
//                result.setErrorList(errorList);
//            }
//        };
//
//        EasyExcel.read(file.getInputStream(), GoodsInfoVo.class, listener)
//                .sheet()
//                .doRead();
//
//        return result;
//    }


}




